# 多阶段构建 - 编译阶段
FROM maven:3.8.4-openjdk-17 AS builder

# 设置工作目录
WORKDIR /build

# 配置Maven使用阿里云镜像
RUN echo '<?xml version="1.0" encoding="UTF-8"?>' > /usr/share/maven/ref/settings.xml && \
    echo '<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"' >> /usr/share/maven/ref/settings.xml && \
    echo '          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' >> /usr/share/maven/ref/settings.xml && \
    echo '          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">' >> /usr/share/maven/ref/settings.xml && \
    echo '  <mirrors>' >> /usr/share/maven/ref/settings.xml && \
    echo '    <mirror>' >> /usr/share/maven/ref/settings.xml && \
    echo '      <id>aliyun</id>' >> /usr/share/maven/ref/settings.xml && \
    echo '      <name>Aliyun Maven Repository</name>' >> /usr/share/maven/ref/settings.xml && \
    echo '      <url>https://maven.aliyun.com/repository/public</url>' >> /usr/share/maven/ref/settings.xml && \
    echo '      <mirrorOf>central</mirrorOf>' >> /usr/share/maven/ref/settings.xml && \
    echo '    </mirror>' >> /usr/share/maven/ref/settings.xml && \
    echo '  </mirrors>' >> /usr/share/maven/ref/settings.xml && \
    echo '</settings>' >> /usr/share/maven/ref/settings.xml

# 复制shared-components
COPY shared-components ./shared-components

# 先构建shared-components
RUN cd shared-components && mvn clean install -DskipTests -B -s /usr/share/maven/ref/settings.xml

# 复制当前服务的pom.xml和源代码
COPY api-gateway/pom.xml ./
COPY api-gateway/src ./src

# 编译当前服务
RUN mvn clean package -DskipTests -B -s /usr/share/maven/ref/settings.xml

# 运行阶段
FROM openjdk:17-jdk-slim

# 设置工作目录
WORKDIR /app

# 从构建阶段复制JAR文件
COPY --from=builder /build/target/*.jar app.jar

# 暴露端口
EXPOSE 8080

# 设置JVM参数
ENV JAVA_OPTS="-Xmx512m -Xms256m"

# 启动应用
CMD ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]

# 健康检查 - 增加启动等待时间
HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=5 \
  CMD curl -f http://localhost:8080/actuator/health || exit 1